<template>
    <div class="container addtemplate">
        <main  class="table-div">
            <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px" class="demo-ruleForm">
              <el-form-item label="模板名称" prop="templateName">
                <el-input v-model="form.templateName"></el-input>
              </el-form-item>
              <el-form-item label="模板标记" prop="templateSign">
                <el-input v-model="form.templateSign"></el-input>
              </el-form-item>
              <el-form-item label="模版热度" prop="passionate">
                <el-input v-model="form.passionate" type="number"></el-input>
              </el-form-item>
              <el-form-item label="模版类型" prop="sort">
                <el-select v-model="form.sort" placeholder="请选择模版类型">
                  <el-option label="节日类" :value="0"></el-option>
                  <el-option label="祝福类" :value="1"></el-option>
                </el-select>
              </el-form-item>
               <el-form-item label="日期分类" prop="datesort">
                <el-select v-model="form.datesort" placeholder="请选择节日类型">
                  <el-option label="阴历" :value="0"></el-option>
                  <el-option label="阳历" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="节日日期" prop="solar" v-if="form.datesort!='0'">
                <el-col :span="11">
                  <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.solar" style="width: 100%;"></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="节日日期" prop="lunar" v-if="form.datesort=='0'">
                <el-col :span="11">
                  <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.lunar" style="width: 100%;"></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="阴历" v-if="form.datesort=='0'">
                <el-col :span="11">
                  <el-input v-model="lunarName" type="text" readonly></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="是否展示">
                <el-switch
                  v-model="form.isshow"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="展示"
                  inactive-text="不展示"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-form-item>
                <el-form-item label="附件上传">
                  <el-upload
                    class="img-uploader"
                    ref="upload"
                    action="#"
                    :on-preview="handlePictureCardPreview"
                    list-type="picture-card"
                    accept="image/*"
                    :fileList='fileList'
                    :limit='1'
                    :on-exceed="maxlimit"
                    :auto-upload="false">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="file.dialogVisible">
                    <img width="100%" :src="file.dialogImageUrl" alt="">
                  </el-dialog>
              </el-form-item>
              <el-form-item>
                <el-button v-if="!id" type="primary" @click="submitAdd('ruleForm')">立即创建</el-button>
                <el-button v-if="id" type="primary" @click="submitEdit('ruleForm')">确认修改</el-button>
              </el-form-item>
            </el-form>
        </main>
    </div>
</template>

<script>
const chineseLunar = require('chinese-lunar')//eslint-disable-line
import { addTemplate, editTemplate, getTemplateDetail } from '@/api/template'
export default {
  data () {
    return {
      id: '',
      file: {
        dialogImageUrl: '',
        dialogVisible: false
      },
      fileList: [],
      solar: '',
      lunarName: '',
      form: {
        templateName: '',
        templateSign: '',
        passionate: 0,
        isshow: 1,
        sort: '',
        datesort: '',
        lunar: '',
        solar: ''
      },
      rules: {
        templateName: [
          { required: true, message: '请输入模版名称', trigger: 'blur' }
        ],
        templateSign: [
          { required: true, message: '请输入模版标记', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请选择模版类型', trigger: 'blur' }
        ],
        datesort: [
          { required: true, message: '请选择节日类型', trigger: 'change' }
        ],
        solar: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        lunar: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    datesort () {
      return this.form.datesort
    },
    lunar () {
      return this.form.lunar
    }
  },
  watch: {
    lunar (newVal, oldVal) {
      if (newVal) {
        var [...ymd] = newVal.split('-')
        var lunar = chineseLunar.solarToLunar(new Date(ymd[0], ymd[1] - 1, ymd[2]))
        this.lunarName = '农历' + chineseLunar.format(lunar, 'YMd')
      } else {
        this.lunarName = ''
      }
    },
    datesort (newVal, oldVal) {
      if (newVal === 0) {
        this.form.solar = ''
      } else {
        this.form.lunar = ''
      }
    }
  },
  methods: {
    maxlimit () {
      this.$message({
        message: '最多添加一张预览图',
        type: 'warning'
      })
    },
    getDetails (id) {
      getTemplateDetail({ id: id }).then(data => {
        if (data.result === 1) {
          this.form.templateName = data.data.templatename
          this.form.passionate = data.data.passionate
          this.form.sort = data.data.sort
          this.form.datesort = data.data.datesort ? 1 : 0
          this.form.solar = new Date(data.data.solar)
          this.form.lunar = data.data.lunar
          this.form.ishow = data.data.ishow ? 1 : 0
          this.form.templateSign = data.data.templateSign
          this.fileList.push({ name: data.data.tempaltePic, url: data.data.tempaltePic })
        } else {
          this.$message({
            message: data.msg,
            type: 'error'
          })
        }
      })
    },
    submitAdd (formName) {
      var upfiles = this.$refs.upload.uploadFiles
      if (upfiles.length === 0) {
        this.$message({
          message: '请上传文件',
          type: 'warning'
        })
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formData = new FormData()
          Object.entries(this.form).map(item => {
            formData.append(item[0], item[1])
          })
          formData.append('file', upfiles[0].raw)
          addTemplate(formData).then((data) => {
            if (data.result === 1) {
              setTimeout(() => {
                this.$router.back()
              }, 1000)
            }
          })
        } else {
          return false
        }
      })
    },
    submitEdit (formName) {
      var upfiles = this.$refs.upload.uploadFiles
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formData = new FormData()
          Object.entries(this.form).map(item => {
            formData.append(item[0], item[1])
          })
          formData.append('id', this.id)
          if (upfiles.length !== 0) {
            formData.append('file', upfiles[0].raw)
          }
          editTemplate(formData).then((data) => {
            if (data.result === 1) {
              setTimeout(() => {
                this.$router.replace({ name: 'TemplateList', params: { page: this.oldPage }})
              }, 1000)
            }
          })
        } else {
          return false
        }
      })
    },
    handlePictureCardPreview (file) {
      this.file.dialogImageUrl = file.url
      this.file.dialogVisible = true
    }
  },
  beforeMount () {
    this.id = this.$route.params.id
    this.oldPage = this.$route.params.page ? this.$route.params.page : ''
    if (this.id) this.getDetails(this.id)
  },
  mounted () {

  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#fff;
$dark_gray:#889aa4;
$light_gray:#eee;
.table-div{
    width:90%;
    margin: 20px auto
}
.title{
    width:90%;
    margin: 10px auto;
    .search-div,.row-div{
      float: left;
    }
    .search-div{
      width: 200px;
      margin-right: 20px
    }
}
.el-upload-list__item{
  height:auto !important;
}
</style>
